package com.agent.service.impl;

import com.agent.entity.Dept;
import com.agent.service.IDeptService;
import com.agent.service.UserService;
import com.agent.util.Constants;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by hg on 2019/1/25.
 */
@Service("scheduleDept")
public class ScheduleDept {

    @Resource(name = "deptServiceImpl")
    IDeptService deptService;


    public void execute(){
        deptService.deleteBySystem();
        syncDept(WxepConstants.REPAIRE_SECRET);
//        syncDept(WxepConstants.ENGINEER_SECRET,WxepConstants.CUSTOMER_AGENT);
    }

    public void syncDept( String secret){
        String accessToken = WXUtil.getToken(WxepConstants.CorpId,secret);
        String url = WxepConstants.GET_DEPTLIST_URL.replace("{accessToken}",accessToken);
        JSONObject result = WXUtil.httpRequest(url, "GET", null);
        if(WxepConstants.SUCCESS_CODE ==result.getInt("errcode")){
            JSONArray jsonArray = result.getJSONArray("department");
            List<Map<String,Object>> deptLists = (List)jsonArray;
            if(deptLists.size()>0){
                deptService.insert(assemblyDeptInfo(deptLists));
            }
        }
    }

    private List<Dept> assemblyDeptInfo(List<Map<String,Object>> deptLists){
        List<Dept> result = new ArrayList<>();
        deptLists.forEach(entry ->{
            Dept dept = new Dept();
            dept.setCreateTime(new Date());
            dept.setDeptName(String.valueOf(entry.get("name")));
            dept.setQywxId(String.valueOf(entry.get("id")));
            dept.setParentId(Integer.parseInt(String.valueOf(entry.get("parentid"))));
            dept.setEnabled(true);
            dept.setOwnerSystem(Constants.SYSTEM);
            result.add(dept);
        });
        return result;
    }
}
